import axios from 'axios'
import { message } from 'ant-design-vue'
import { webSocketClient } from '@renderer/network/notice'
const instance = axios.create({
  headers: {
    'Content-Type': 'application/json'
  }
})

function freshtoken(token) {
  window.localStorage.setItem('token', token)
}



instance.interceptors.request.use(
  function (config) {
    let baseUrl = import.meta.env.MODE == 'development'
      ? 'http://localhost:5173/api'
      : 'https://boerman.cc'
    config.baseURL = baseUrl
    const token = window.localStorage.getItem('token')
    if (token) config.headers.Authorization = `Bearer ${token}`
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  function (response) {
    const { data } = response
    if (data.message) {
      message.success(data.message)
    }
    return data
  },
  function (error) {
    const { status, data } = error.response
    switch (status) {
      case 444:
        //刷新令牌
        freshtoken(error.response.headers["authorization"])
      case 422:
        //表单验证失败
        if (data) {
          message.error(data)
        }
        break
      case 401:
        message.error('请先登录')
        //将长连接关闭
        webSocketClient.value = null;
        window.location.href = '#/auth'
        break
      case 500:
        if (data.error) {
          message.error(data.error)
          return
        }
        message.error('服务器错误，请检查')
        break
      case 403:
        message.error(data.error)
        break
    }

    return Promise.reject(error)
  }
)

export default instance
